const express = require("express");
const { createServer } = require("node:http");
const { join } = require("node:path");
const app = express();
const server = createServer(app);
const { Server } = require("socket.io"); //socket.io
var router = express.Router();
const cors = require('cors');
const path = require('path')
app.use(cors());
app.use('/uploads',express.static(path.join(__dirname, '/uploads')));
// 引入 fs 模块
const fs = require('fs')
const multer = require('multer');

const io = new Server(server, { cors: true },{ connectionStateRecovery: {} });


app.get("/", (req, res) => {
  res.send("<h1>Hello world</h1>");
});

app.get("/", (req, res) => {
  res.sendFile(join(__dirname, "index.html"));
});

const storage = multer.diskStorage({
  destination: (req, file, cb) => {
      const uploadDir = join(__dirname, 'uploads');
      if (!fs.existsSync(uploadDir)) {
          fs.mkdir(uploadDir, { recursive: true }, (err) => {
              if (err) {
                  return cb(err);
              }
              cb(null, uploadDir);
          });
      } else {
          cb(null, uploadDir);
      }
  },
  filename: (req, file, cb) => {
      const buf = Buffer.from(file.originalname, 'latin1');
      const fileName = buf.toString('utf-8');
      cb(null, Date.now() + '-' + fileName);
  },
});

const upload = multer({ storage });

app.post('/upload', upload.single('image'), (req, res) => {
  const imagePath = req.file.path;
  // 从请求中获取用户信息
  const sender = req.body.username;
  io.emit('imageMessage', { path: imagePath, isUploaded: true, username: sender });
  res.send('图片上传成功');
});

io.on('connection', (socket) => {
  socket.on('message', (dispatcher, user) => {
      console.log(dispatcher, user);
      io.emit('message', dispatcher, user);
  });

  socket.on('imageMessage', async (imageData, user) => {
      const base64Data = imageData.replace(/^data:image\/\w+;base64,/, '');
      const buffer = Buffer.from(base64Data, 'base64');
      const uploadDir = join(__dirname, 'uploads');
      try {
          await fs.access(uploadDir);
      } catch (error) {
          await fs.mkdir(uploadDir, { recursive: true });
      }
      const imageName = Date.now() + '-' + encodeURIComponent(imageData.match(/filename="([^"]+)"/)[1]);
      const imagePath = join(uploadDir, imageName);
      // const imagePath = join(uploadDir, `${Date.now()}.png`);
      try {
          await fs.writeFile(imagePath, buffer);
          io.emit('imageMessage', { path: imagePath, isUploaded: false });
      } catch (error) {
          console.error('保存图片时出现错误：', error);
      }
  });
});

server.listen(3001, () => {
  console.log("server running at http://localhost:3001");
});
module.exports = router;

